package com.arvato.wxwork.controller.admin.member;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.arvato.common.config_bean.FilehomeConfig;
import com.arvato.common.util.ExportExcelUtil;
import com.arvato.common.util.ImportExcelUtil;
import com.arvato.minipro.bean.bean_dto.common.PageData;
import com.arvato.minipro.bean.bean_dto.common.Query;
import com.arvato.minipro.bean.bean_dto.common.Result;
import com.arvato.wxwork.bean.bean_do.member.WxworkTagDo;
import com.arvato.wxwork.bean.bean_vo.member.WxworkManualTagVo;
import com.arvato.wxwork.bean.bean_vo.member.WxworkTagVo;
import com.arvato.wxwork.service.member.WxworkTagService;

/**
 * 标签管理
 * 
 * @author ding
 */
@RestController
@RequestMapping("/wxwork/admin/tag")
public class WxworkTagAdminController {

	private Logger logger = LoggerFactory.getLogger(WxworkTagAdminController.class);
	@Autowired
	private WxworkTagService wxworkTagService;



	/**
	 * 分页查询
	 * 
	 * @param req
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getTagList")
	public PageData getTagList(HttpServletRequest req, @RequestParam Map<String, Object> param) {
		logger.info("调用getTagList接口");
		Query query = new Query(param);
		PageData pageData = wxworkTagService.listTagByQuery(query, query.getPageNum(), query.getPageSize());
		return pageData;
	}

	/**
	 * 删除tag
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/deleteTag")
	public Result deleteTag(String id) {
		logger.info("调用deleteTag接口");
		int row = wxworkTagService.delete(id);
		if (row == 1) {
			return Result.success(row);
		}
		return Result.fail("操作失败");
	}

	/**
	 * 查询tag
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getTagById")
	public Result getTagById(String id) {
		logger.info("调用getTagById接口");
		Query query = new Query();
		query.put("id", id);
		WxworkTagVo tag = wxworkTagService.getTagById(id);
		return Result.success(tag);
	}

	/**
	 * 新增标签
	 * 
	 * @param dto
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/insertTag")
	public Result insertTag(WxworkTagDo dto) {
		logger.info("调用insertTag接口");
		Query query = new Query();
		query.put("name", dto.getTagName());
		List<WxworkTagVo> list = wxworkTagService.listTagByQuery(query);
		if (null != list) {
			int row = wxworkTagService.insert(dto);
			if (row == 1) {
				return Result.success(dto.getId());
			}
		}
		return Result.fail("操作失败");
	}

	/**
	 * 修改标签
	 * 
	 * @param dto
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateTag")
	public Result updateTag(WxworkTagDo dto) {
		logger.info("调用updateTag接口");
		Query query = new Query();
		query.put("name", dto.getTagName());
		List<WxworkTagVo> list = wxworkTagService.listTagByQuery(query);
		if (null != list) {
			int row = wxworkTagService.update(dto);
			if (row == 1) {
				return Result.success(dto.getId());
			}
		}
		return Result.fail("操作失败");
	}

	@RequestMapping("exportTag")
	public void exportList(HttpServletResponse response, String ids) {
		String fileName = "标签库";
		// 列名
		String columnNames[] = { "标签名称" };
		// map中的key
		String keys[] = { "tagName" };
		try {
			ExportExcelUtil.start_download(response, fileName, wxworkTagService.listTagByQuery(new Query()), columnNames,
					keys);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 导入excel表
	 * 
	 * @version 1.0
	 * @since 1.0
	 */
	@RequestMapping(path = "/importTag")
	public Result uploadExcel(@RequestParam("file") MultipartFile file) {
		try {
			// 先把文件存储起来 存储到本地
			String fileName = +System.currentTimeMillis() + "." + file.getOriginalFilename().split("\\.")[1];
			if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) {
				// 如果不是excel文件 直接返回上传失败
				return Result.fail("仅支持Excel文件类型。");
			}
			// 先确保服务器上有 FilehomeConfig.FILEHOME 这么一个文件夹
			File excelFile = new File(FilehomeConfig.FILEHOME + fileName);
			if (!excelFile.exists()) {
				excelFile.createNewFile();
				file.transferTo(excelFile);
			}
			List<List<Object>> excleDataList = ImportExcelUtil.readExcel(excelFile);
			List<WxworkTagVo> wxworkTagDoList = new ArrayList<WxworkTagVo>();
			for (int i = 1; i < excleDataList.size(); i++) {
				List<Object> obj = excleDataList.get(i);
				WxworkTagVo dto = new WxworkTagVo();
				dto.setTagName(obj.get(0).toString());
				wxworkTagDoList.add(dto);
			}
			// 获取数据库已有的tag去重 List<WxworkTagDo>
			List<WxworkTagVo> existTagList = wxworkTagService.listTagByQuery(new Query());
			List<WxworkTagVo> newTagList = new ArrayList<WxworkTagVo>();
			newTagList.addAll(existTagList);
			newTagList.addAll(wxworkTagDoList);
			Set<WxworkTagVo> hashVo = new HashSet<WxworkTagVo>();
			for (int i = 0; i < newTagList.size(); i++) {
				hashVo.add(newTagList.get(i));
			}
			Iterator<WxworkTagVo> it = hashVo.iterator();
			wxworkTagService.importExcelData(it);
			return Result.success("Excel文件上传保存成功。");
		} catch (IllegalStateException | IOException e) {
			logger.error(e.getMessage());
			return Result.fail("Excel文件上传保存失败。");
		} catch (Exception e) {
			logger.error(e.getMessage());
			return Result.fail("Excel文件上传保存失败。");
		}
	}

	/**
	 * 手动标签管理详情
	 * 
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getManualTagById")
	public Result getManualTagById(String id) {
		logger.info("调用getManualTagList接口");
		Query query = new Query();
		query.put("id", id);
		List<WxworkManualTagVo> tag = wxworkTagService.getManualTagList(query);
		if (null != tag && tag.size() > 0) {
			return Result.success(tag.get(0));
		}
		return null;
	}

	@RequestMapping("exportManualTag")
	public void exportManualTag(HttpServletResponse response) {
		String fileName = "标签库";
		// 列名
		String columnNames[] = { "标签名称", "使用频次" };
		// map中的key
		String keys[] = { "tagName", "tagCount" };
		try {
			ExportExcelUtil.start_download(response, fileName, wxworkTagService.getManualTagList(new Query()),
					columnNames, keys);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("getDataFromCrm")
	public void getDataFromCrm(HttpServletResponse response) {
		 // helloSender.send();
	}

	
}
